package com.carryon.modules.sj.execute;

import java.lang.reflect.Method;
import java.util.Map;

import com.carryon.modules.sj.Execute;
import com.carryon.modules.sj.SJ;
import com.carryon.modules.sj.exception.InternalServerException;

/**
 * @author Helin
 * @mail hl_0074@sina.com
 * @date 2011-9-28
 * 
 */
public class PrimitiveExecute implements Execute {

	private Class<?> clazz;
	private String method;

	public PrimitiveExecute(Class<?> clazz, String method) {

		this.clazz = clazz;
		this.method = method;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void execute(SJ sj) throws Exception {

		Object instance = null;
		try {
			instance = clazz.newInstance();
		} catch (Exception e) {
			throw new InternalServerException("class not found:", e);
		}

		Method invoke = null;
		try {
			invoke = clazz.getMethod(this.method, Map.class);
		} catch (Exception e) {
			throw new InternalServerException("method not found: Map<String,Object> " + this.clazz.getCanonicalName() + "." + this.method
					+ "(Map<String,Object> param)", e);
		}
		if (!Map.class.isAssignableFrom(invoke.getReturnType())) {
			throw new InternalServerException("method not found: HashMap<String,Object> " + this.clazz.getCanonicalName() + "."
					+ this.method + "(HashMap<String,Object> param)");
		}

		try {
			invoke.setAccessible(true);
			Map<String, Object> resp = (Map<String, Object>) invoke.invoke(instance, sj.getRequest());
			sj.getResponse().putAll(resp);
		} catch (Exception e) {
			throw new Exception(e.getCause().getMessage(), e);
		}
	}

}
